/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.txusballesteros.demo;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.app.Context;

/**
 * Space is a lightweight View subclass that may be used to create gaps between components
 * in general purpose layouts.
 */
public final class Space extends Component implements Component.DrawTask {
    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttrSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr);
        if (getVisibility() == VISIBLE) {
            setVisibility(INVISIBLE);
        }
        addDrawTask(this);
    }

    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttrSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
        addDrawTask(this);
    }

    /**
     * {@inheritDoc}
     */
    public Space(Context context, AttrSet attrs) {
        this(context, attrs, 0);
        addDrawTask(this);
    }

    /**
     * {@inheritDoc}
     *
     * @param context Context
     */
    public Space(Context context) {
        this(context, null);
    }

    private static int getDefaultSize2(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
            case MeasureSpec.UNCONSTRAINT:
                result = size;
                break;
            case MeasureSpec.NOT_EXCEED:
                result = Math.min(size, specSize);
                break;
            case MeasureSpec.PRECISE:
                result = specSize;
                break;
        }
        return result;
    }

    /**
     * onMeasure
     *
     * @param widthMeasureSpec integer
     * @param heightMeasureSpec integer
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setEstimatedSize(
                getDefaultSize2(getEstimatedWidth(), widthMeasureSpec),
                getDefaultSize2(getEstimatedHeight(), heightMeasureSpec));
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        onMeasure(getEstimatedWidth(), getEstimatedHeight());
    }
}
